<template>
<div>
  <el-steps :active="active" finish-status="success" align-center>
    <el-step title="创建项目"></el-step>
    <el-step title="上传视频"></el-step>
    <el-step title="编码数据"></el-step>
    <el-step title="分析结果"></el-step>
  </el-steps>
  <el-divider></el-divider>
  <el-skeleton :loading=loading :rows="10" animated />
  <div v-show="active!==0">
    <el-card shadow="hover">
      <el-descriptions title="项目信息">
        <el-descriptions-item label="项目名">{{this.project.projectName}}</el-descriptions-item>
        <el-descriptions-item label="项目类型">S-T分析</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{this.project.createTime}}</el-descriptions-item>
      </el-descriptions>
    </el-card>
  </div>
  <div v-show="active === 0 && loading===false">
    <el-card shadow="hover">
      <el-form ref="projectFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目名" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名" />
        </el-form-item>
        <el-form-item label="项目类型" prop="projectType">
          <el-select v-model="form.projectType">
            <el-option  key="ST" label="S-T分析" value="ST"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">创建项目</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <div v-show="active===1" style="width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between" >
    <el-card style="width: 48%;">
      <div slot="header">
        <span><b>上传视频</b></span>
      </div>
      <VideoUpload ref="videoUpload"></VideoUpload>
    </el-card>
    <el-card style="width: 48%">
      <div slot="header">
        <span><b>设置参数</b></span>
      </div>
      <el-form ref="stConfigFormRef" :model="stConfig" :rules="stConfigRules" label-width="120px">
        <el-form-item label="采样间隔(s)" prop="interval">
          <el-input-number v-model="stConfig.interval"  :min="1" :max="60"></el-input-number>
        </el-form-item>
        <el-form-item label="采样开始时刻" prop="startTime">
          <el-time-select placeholder="起始时间"
              v-model="stConfig.startTime"
              :picker-options="{
                start:  this.time.startTime,
                step: formatTime(stConfig.interval),
                end: this.time.endTime
              }">
          </el-time-select>
        </el-form-item>
        <el-form-item label="采样结束时刻" prop="endTime">
          <el-time-select placeholder="结束时间"
                          v-model="stConfig.endTime"
                          :picker-options="{
                start: this.time.startTime,
                step: formatTime(stConfig.interval),
                end: this.time.endTime,
                minTime: stConfig.startTime
              }">
          </el-time-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="next">下一步</el-button>
          <el-button @click="resetForm2">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
  <div v-show="active===2"  style="width: 100%;display: flex;flex-direction: row;margin-top: 20px;justify-content: space-between">
    <el-card style="width: 48%;">
      <div slot="header">
        <span><b>播放视频</b></span>
      </div>
      <video-player style="width: 97%"
                    class="video-player vjs-custom-skin"
                    ref="videoPlayer"
                    @canplay="onPlayerCanplay($event)"
                    @timeupdate="onPlayerTimeupdate($event)"
                    :options="playerOptions"/>
    </el-card>
    <el-card style="width: 48%;">
      <div slot="header">
        <span><b>编码区域</b></span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="startEncode">开始编码</el-button>
      </div>
      <div style="display: flex;flex-direction: column;">
        <div style="margin-bottom: 5px">编码时间间隔：{{this.st.interval}}s</div>
        <div>
          当前编码时间段：<el-tag>{{ this.encodeTime.startTime }}</el-tag> -- <el-tag type="success">{{ this.encodeTime.endTime }}</el-tag>
        </div>
        <el-divider></el-divider>
        <el-form ref="encodeFormRef" label-width="90px" :model="encode" :rules="encodeRules">
          <el-form-item label="选择编码" prop="code">
            <el-radio v-model="encode.code" label="S">学生行为</el-radio>
            <el-radio v-model="encode.code" label="T">教师行为</el-radio>
          </el-form-item>
          <el-form-item>
            <el-button v-waves plain type="primary"  @click="preCode" >上一个</el-button>
            <el-button v-waves v-if="!finishFlag" plain type="success" @click="nextCode" >下一个</el-button>
            <el-button v-waves v-else type="success" @click="encodeSt" >完成</el-button>
          </el-form-item>
        </el-form>
        <el-divider/>
        <div v-if="preFlag">
          <div>
            上个编码时间段：
            <el-tag>
              {{ this.preTime.startTime }}
            </el-tag>
            --
            <el-tag type="success">
              {{ this.preTime.endTime }}
            </el-tag>
          </div>
          <div style="margin-top: 10px">
            上个编码内容：{{this.preTime.preCode}}
          </div>
        </div>
      </div>
    </el-card>
  </div>
  <div v-show="active===3 || active===4" style="width: 100%">
    <el-alert title="教学模式划分规则：练习型Rt<=0.3，讲授型Rt>=0.7，对话型Ch>=0.4，混合型0.3<Rt<0.7同时Ch<0.4" :closable="false" type="success" show-icon style="margin-bottom: 10px;margin-top: 10px"></el-alert>
    <el-card shadow="always">
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-statistic group-separator=","
                          :precision="8"
                          :value="st.rt"
                          title="教师行为占有率(Rt)">
              <template slot="prefix">
                <i class="el-icon-s-data" style="color: blue"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic :value="st.ch"
                          :precision="8"
                          title="行为转换率(Ch)"
                          group-separator=",">
              <template slot="prefix">
                <i class="el-icon-s-data" style="color: blue"></i>
              </template>
            </el-statistic>
          </div>
        </el-col>
        <el-col :span="6">
          <div style="display: flex;flex-direction: column;align-items: center">
            <el-statistic title="教学模式"></el-statistic>
            <div>{{st.mode}}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div>
            <el-statistic :value="st.time"
                          title="分析耗时(ms)"
                          group-separator=",">
              <template slot="prefix">
                <i class="el-icon-time" style="color: blue"></i>
              </template>
              <template slot="suffix">
                ms
              </template>
            </el-statistic>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
  <div v-show="active === 3" style="width: 100%">
    <el-button v-waves plain type="primary" style="width:10%;float: left;margin-top: 20px" @click="pre" >上一步</el-button>
    <el-button v-waves type="success" style="width:10%;float: right;margin-top: 20px" @click="finish" >完成</el-button>
  </div>
  <div v-show="active === 4" style="width: 100%">
    <el-result icon="success" title="分析成功" subTitle="需要下载或预览源文件请点击下方按钮">
      <template slot="extra">
        <el-button type="primary"  plain  icon="el-icon-download" size="medium" @click="download">下载</el-button>
        <el-button type="info" plain icon="el-icon-files" size="medium" @click="preview">预览</el-button>
      </template>
    </el-result>
  </div>
</div>
</template>

<script>
import {addProject, getProject} from "@/api/myProject";
import {encodeSt, finish, getInfo, pre, stConfig} from "@/api/st";
import VideoUpload from "@/component/VideoUpload.vue";
import pubsub from "pubsub-js";
import {formatTime, timeToSec} from "@/utils/date";
import Waves from "@/directives/waves/waves";

export default {
  name: "ST",
  directives:{Waves},
  components: {VideoUpload},
  data(){
    return{
      finishFlag:false,
      startFlag:false,
      encode:{
        //当前编码数据
        code:''
      },
      preFlag:false,
      //编码数据
      codeList:[],
      //上个编码时间段
      preTime:{
        startTime:'',
        endTime:'',
        preCode:''
      },
      //编码时间段
      encodeTime:{
        startTime:"",
        endTime:""
      },
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, //如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: "video/mp4",// 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
          src: "" // url地址
        }],
        poster: "", // 你的封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true  // 全屏按钮
        }
      },
      //时间选择器
      time:{
        startTime:'00:00',
        endTime:'',
        step:'',
      },
      stConfig:{
        interval:5,
        id:'',
        duration:'',
        endTime:"00:00",
        startTime:'00:00'
      },
      loading:false,
      id:this.$route.query.id,
      active: 0,
      form:{
        projectName:"",
        projectType:""
      },
      project:{},
      st:{
        id:'',
        stStatus:'',
      },
    }
  },
  methods:{
    formatTime,
    download(){
      window.location.href = this.st.codeTable;
    },
    preview(){
      var url =  this.st.codeTable; //要预览文件的访问地址
      // eslint-disable-next-line no-undef
      window.open('http://127.0.0.1:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(url)));
    },
    finish(){
      finish(this.st.id).then(()=>{
        this.active=4
      })
    },
    //分析结果页面点击上一步
    pre(){
      pre(this.st.id).then(()=>{
        this.playerOptions.sources[0].src=this.st.videoUrl
        this.playerOptions.poster=this.st.videoUrl+"?x-oss-process=video/snapshot,t_1000,m_fast"
        this.encodeTime.startTime=this.st.startTime
        this.encodeTime.endTime=this.st.endTime
        this.active=2
      })
    },
    //完成分析，上传数据
    encodeSt(){
      console.log(this.codeList)
      encodeSt(this.st.id, {
        codeList : this.codeList
      }).then(()=>{
        this.$notify({
          title: 'EasyCTBA',
          message: '分析成功！',
          type: 'success',
          duration: '1000',
          offset: 100
        });
        this.getST()
      })
    },
    getCodeLabel(code){
      if (code==="S"){
        return "S 学生行为"
      }else if (code==="T"){
        return "T 教师行为"
      }else {
        return "NULL"
      }
    },
    //上一个编码
    preCode(){
      if (this.startFlag===false){
        this.$notify({
          title: 'EasyCTBA',
          message: '请点击开始编码！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }else {
        //未检测到上个编码
        if (this.codeList.length === 0) {
          this.$notify({
            title: 'EasyCTBA',
            message: '没有上个编码！',
            type: 'error',
            duration: '3000',
            offset: 100
          });
        } else {
          //回退编码信息
          this.encodeTime.endTime=this.encodeTime.startTime
          this.encodeTime.startTime=formatTime(timeToSec(this.encodeTime.endTime)-this.st.interval)
          this.encode.code=this.codeList.pop()
          //没有上个编码了
          if (this.codeList.length === 0){
            this.preFlag=false
          }else {
            //回退上一个编码信息
            this.preTime.endTime=this.encodeTime.startTime
            this.preTime.startTime=formatTime(timeToSec(this.preTime.endTime)-this.st.interval)
            this.preTime.preCode=this.getCodeLabel(this.codeList.at(-1))
          }
        }
      }
    },
    //下一个编码
    nextCode(){
      if (this.startFlag===false){
        this.$notify({
          title: 'EasyCTBA',
          message: '请点击开始编码！',
          type: 'error',
          duration: '3000',
          offset: 100
        });
      }else{
        this.$refs.encodeFormRef.validate(valid => {
          if (valid) {
            //修改上个编码时间段
            if (this.codeList.length===0){
              this.preFlag=true
            }
            this.preTime.startTime=this.encodeTime.startTime
            this.preTime.endTime=this.encodeTime.endTime
            this.preTime.preCode=this.getCodeLabel(this.encode.code)

            this.codeList.push(this.encode.code)
            //修改编码时间段
            this.encodeTime.startTime=this.encodeTime.endTime
            this.encodeTime.endTime=formatTime(timeToSec(this.encodeTime.startTime)+this.st.interval)

            this.$refs.videoPlayer.player.play()

            //编码时间超过视频时间，结束编码
            if (timeToSec(this.encodeTime.endTime)>this.st.duration){
              this.finishFlag=true;
            }
          }
        })
      }
    },
    //开始编码
    startEncode(){
      this.startFlag=true;
      this.$refs.videoPlayer.player.currentTime(timeToSec(this.st.startTime))
      this.$refs.videoPlayer.player.play()
    },
    //视频时间变化回调
    onPlayerTimeupdate(player){
      if (player.currentTime() >= timeToSec(this.encodeTime.endTime)){
        //当前时间大于编码结束时间
        player.pause()
      }
    },
    //视频准备完毕回调
    onPlayerCanplay(player){
      console.log(player.currentTime())
    },
    //在上传数据界面点击下一步
    next(){
      this.stConfig.id=this.st.id
      stConfig(this.stConfig).then(()=>{
        this.getST()
        this.$notify({
          title: 'EasyCTBA',
          message: '操作成功！',
          type: 'success',
          duration: '2000',
          offset: 100
        });
      })
    },
    resetForm2(){
      this.stConfig.interval=5
      this.stConfig.startTime="00:00"
      this.stConfig.endTime=formatTime(this.stConfig.duration)
    },
    setTime(data){
      this.stConfig.duration=data

      this.time.endTime=formatTime(data)
      this.time.startTime="00:00"
    },
    getST(){
      getInfo(this.project.id).then(res=>{
        this.st=res.data
        if (this.st.stStatus==="upload"){
          this.active=1
        }else if (this.st.stStatus==="encode"){
          this.active=2
        }else if (this.st.stStatus==="result"){
          this.active=3;
        }else if (this.st.stStatus==="download"){
          this.active=4
        } else {
          this.active=0
        }
      });
    },
    //提交表单
    submitForm(){
      this.$refs.projectFormRef.validate(valid => {
        if (valid) {
          addProject(this.form).then( res =>{
            this.getProject(res.data)
            this.active=1
            this.$notify({
              title: 'EasyCTBA',
              message: '新建成功！',
              type: 'success',
              duration: '2000',
              offset: 100
            });
          })
        }
      })
    },
    //获取项目详情
    getProject(id){
      getProject(id).then((res)=>{
        this.project=res.data
        this.getST() //同步执行
      });
      if (this.project==={}){
        this.$notify({
          title: 'EasyCTBA',
          message: '参数异常！',
          type: 'error',
          duration: '2000',
          offset: 100
        });
      }
    },
    //重置表单
    resetForm(){
      this.form={}
    },
  },
  created() {

  },
  mounted() {
    this.pubId = pubsub.subscribe('duration', (_,data) => {
      this.setTime(data)
    })



    const id=this.id
    if (id) {
      this.loading = true
      getProject(id).then((res)=>{
        this.project=res.data
        getInfo(this.project.id).then(res=>{
          this.st=res.data
          //传递参数给视频上传组件
          pubsub.publish('initVideo', {
            url:this.st.videoUrl,
            id:this.st.id,
            type:'ST'
          })

          if (this.st.stStatus==="upload"){
            this.active=1
          }else if (this.st.stStatus==="encode"){

            this.playerOptions.sources[0].src=this.st.videoUrl
            this.playerOptions.poster=this.st.videoUrl+"?x-oss-process=video/snapshot,t_1000,m_fast"
            this.encodeTime.startTime="00:00"
            this.encodeTime.endTime=formatTime(timeToSec(this.encodeTime.startTime)+this.st.interval)
            this.active=2

          }else if (this.st.stStatus==="result"){
            this.active=3;
          }else if (this.st.stStatus==="download"){
            this.active=4
          } else {
            this.active=0
          }
          this.loading=false
        });
      });
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    pubsub.unsubscribe(this.pubId)
  },
  computed:{
    rules(){
      return{
        projectName: [
          { required: true, message: "项目名不能为空", trigger: "blur" }
        ],
        projectType: [
          { required: true, message: "项目类型不能为空", trigger: "change" }
        ],
      }
    },
    stConfigRules(){
      return{
        startTime:[
          { type: 'date', required: true, message: '请选择开始时间', trigger: 'change' }
        ],
        endTime:[
          { type: 'date', required: true, message: '请选择结束', trigger: 'change' }
        ],
        interval:[
          { type: 'number', required:true, message: '请输入正确数据', trigger: 'blur' }
        ]
      }
    },
    encodeRules(){
      return{
        code:[
          {required:true,message:'请选择编码类型',trigger:'blur'}
        ]
      }
    }
  }
}
</script>

<style scoped>

</style>